<script setup>
	//是否显示倒计时

	import { ref } from 'vue'
	import { LoginApi, getCodeApi } from '@/apis/user'
	import { useUserStore } from '@/stores/user'
	//用户的相关信息
	const userStore = useUserStore()
	//显示倒计时
	const showCountDown = ref(false)
	//获取验证码
	const getCode = async () => {
		try {
			//校验表单的部分字段
			await form.value.validateField(['mobile'])
			//校验通过以后  再去修改倒计时
			showCountDown.value = true
			//ToDo 获取验证码
			const res = await getCodeApi({
				mobile: formData.value.mobile,
				type: 'login',
			})
			console.log(res)
			formData.value.code = res.code
		} catch (e) {
			console.log(e)
		}
	}

	//获取表单元素
	const formData = ref({
		mobile: '',
		code: '',
	})
	//表单校验
	const form = ref()

	// 验证表单数据的规则
	const formRules = {
		mobile: {
			rules: [
				{ required: true, errorMessage: '请填写手机号码' },
				{ pattern: '^1\\d{10}$', errorMessage: '手机号码格式不正确' },
			],
		},
		code: {
			rules: [
				{ required: true, errorMessage: '请输入验证码' },
				{ pattern: '^\\d{6}$', errorMessage: '验证码格式不正确' },
			],
		},
	}

	//是否勾选协议
	const isAgree = ref(false)
	//实现登录
	const Login = async () => {
		if (!isAgree.value) {
			return uni.showToast({
				title: '请勾选用户协议',
				icon: 'error',
			})
		}
		try {
			await form.value.validate()
			//调用登录接口  实现登录
			const res = await LoginApi({
				mobile: formData.value.mobile,
				code: formData.value.code,
			})

			//持久化Token
			userStore.token = res.token
			//提示用户
			uni.showToast({
				title: '登录成功',
				icon: 'success',
			})
			//跳转页面
			uni.switchTab({
				url: '/pages/my/index',
			})
		} catch (e) {
			//TODO handle the exception
			console.log(e)
		}
	}
	const radioChange = () => {
		isAgree.value = !isAgree.value
	}
</script>

<template>
	<uni-forms class="login-form" ref="form" :model="formData" :rules="formRules">
		<uni-forms-item name="mobile">
			<uni-easyinput
				v-model="formData.mobile"
				:input-border="false"
				:clearable="false"
				placeholder="请输入手机号"
				placeholder-style="color: #C3C3C5"
			/>
		</uni-forms-item>
		<uni-forms-item name="code">
			<uni-easyinput
				v-model="formData.code"
				:input-border="false"
				:clearable="false"
				placeholder="请输入验证码"
				placeholder-style="color: #C3C3C5"
			/>
			<text v-if="!showCountDown" @tap="getCode" class="text-button">获取验证码</text>
			<button v-else class="text-button">
				<uni-countdown
					:show-day="false"
					:hour="false"
					:minute="false"
					:second="10"
					@timeup="showCountDown = false"
					color="#16c2a3"
				></uni-countdown>
			</button>
		</uni-forms-item>

		<view class="agreement">
			<radio :checked="isAgree" @tap="radioChange" color="#16C2A3" />
			我已同意
			<text class="link">用户协议</text>
			及
			<text class="link">隐私协议</text>
		</view>

		<button @tap="Login" class="uni-button">登 录</button>
	</uni-forms>
</template>

<script>
	export default {
		options: {
			styleIsolation: 'shared',
		},
	}
</script>

<style lang="scss">
	@import './styles.scss';
</style>
